/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdd.facades.persistence;

import com.sdd.entities.Category;
import com.sdd.entities.Category_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author tpgalan
 */
@Stateless
public class CategoryPersistenceFacade extends AbstractPersistenceFacade<Category>{

    @PersistenceContext(unitName = "SDDStore-ejbPU")
    private EntityManager em;
    
    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CategoryPersistenceFacade() {
        super(Category.class);
    }
    
    public List<Category> getMainCats(){
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Category> query = builder.createQuery(Category.class);
        Root<Category> c = query.from(Category.class);
        /**
         * tpgalan dice:
         * ojo con los metodos de builder: en este caso, no vale hacer
         * builder.equal(c.get("father"),null) porque lo que debe
         * hacer es tratar de instanciar ambos campos de la comparación
         * y entonces peta con el null...
         * Así que lo suyo es emplear el método isNull :)
         */
        
        //query.select(c).where(builder.isNull(c.get("father")));
        query.select(c).where(builder.isNull(c.get(Category_.father)));
        //getEntityManager().creatº("ddd").setFirstResult(1).setMaxResults(10).get
        return getEntityManager().createQuery(query).getResultList();
    }
    
    public List<Category> getChildCats(Category father){
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Category> query = builder.createQuery(Category.class);
        Root<Category> c = query.from(Category.class);
        //query.select(c).where(builder.equal(c.get("father").get("id"), father.getId()));
        query.select(c).where(builder.equal(c.get(Category_.father).get(Category_.id), father.getId()));
        return getEntityManager().createQuery(query).getResultList();
    }
    
    public Category getCategory(String name){
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Category> query = builder.createQuery(Category.class);
        Root<Category> c = query.from(Category.class);
        query.select(c).where(builder.equal(c.get(Category_.name), name));
        List<Category> resultList = getEntityManager().createQuery(query).getResultList();
        if(resultList!=null && resultList.size()>0){
            return resultList.get(0);
        }else
            return null;
    }
}
